import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化 WebDriver
driver = webdriver.Chrome()

# 打开京东首页
driver.get("https://www.jd.com")

# 等待页面加载完成
try:
    wait = WebDriverWait(driver, 20)  # 增加等待时间到 20 秒
    # 等待页面中的某个元素加载完成，这里以导航栏的“家电”为例
    house_device = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="J_cate"]/ul/li[4]/a[1]')))

    # 创建 ActionChains 对象并执行鼠标悬停操作
    action = ActionChains(driver)
    action.move_to_element(house_device).perform()

    # 休眠 5 秒，观察悬停效果
    time.sleep(5)

    # 打印成功证明
    print("鼠标悬停操作成功完成！")

except Exception as e:
    print(f"发生错误：{e}")
    # 如果第一次尝试失败，可以尝试重试
    try:
        print("尝试重新加载页面并重试...")
        driver.refresh()
        wait = WebDriverWait(driver, 20)  # 再次增加等待时间
        house_device = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="J_cate"]/ul/li[4]/a[1]')))
        action = ActionChains(driver)
        action.move_to_element(house_device).perform()
        time.sleep(5)
        print("鼠标悬停操作重试成功！")
    except Exception as e:
        print(f"重试失败：{e}")
finally:
    # 截图保存
    driver.save_screenshot("mouse_hover.png")

    # 关闭浏览器
    driver.quit()
